"use strict";

import Vue from 'vue';
import axios from "axios";
// import qs from 'qs';

// Full config:  https://github.com/axios/axios#request-config
// axios.defaults.baseURL = '/api';
// axios.defaults.headers.common['Authorization'] = AUTH_TOKEN;
// axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';

let config = {
    baseURL: process.env.VUE_APP_API,
    timeout: 60 * 1000, // Timeout
    withCredentials: false, // Check cross-site Access-Control
};

const _axios = axios.create(config);

// const CancelToken = axios.CancelToken;
// const requestMap = new Map();

_axios.interceptors.request.use(
    function (config) {
        // 防止重复提交
        // const keyString = qs.stringify(Object.assign({}, {
        //     url: config.url,
        //     method: config.method
        // }, config.data));
        // if (requestMap.get(keyString)) {
        //     config.cancelToken = new CancelToken(cancel => {
        //         cancel('请勿重复提交，保持至少一秒的间隔');
        //     })
        // }
        // requestMap.set(keyString, true);
        // setTimeout(() => {
        //     requestMap.set(keyString, false);
        // }, 300);
        // Object.assign(config, {
        //     _keyString: keyString
        // });

        // 登录完成后，所有的请求，都会自动添加token请求头
        let userInfo = JSON.parse(sessionStorage.getItem("isLogin"))
        config.headers["token"] = userInfo ? userInfo._id : '';

        // 对于post put delete请求，data进行序列化
        // if (config.method === 'post' || config.method === 'put' || config.method === 'delete') {
        //     config.data = qs.stringify(config.data);
        // }
        return config;
    },
    function (error) {
        // Do something with request error
        return Promise.reject(error);
    }
);

// Add a response interceptor
_axios.interceptors.response.use(
    function (response) {
        // Do something with response data
        return response;
    },
    function (error) {
        console.error(error);
        // Do something with response error
        return Promise.reject(error);
    }
);

Plugin.install = function (Vue) {
    Vue.axios = _axios;
    window.axios = _axios;
    Object.defineProperties(Vue.prototype, {
        axios: {
            get() {
                return _axios;
            }
        },
        $axios: {
            get() {
                return _axios;
            }
        },
    });
};

Plugin.axios = _axios;

Vue.use(Plugin)

export default Plugin;